# itertools 迭代器高效函数

# 内置函数 创建迭代器
for i in iter([1, 2, 3]):
    print(i)

import itertools
import operator

data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
# 执行 加法
print(list(itertools.accumulate(data)))  # [3, 7, 13, 15, 16, 25, 25, 32, 37, 45]
# 执行 最大值
print(list(itertools.accumulate(data, max)))  # [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]
# 执行乘积
print(list(itertools.accumulate(data, operator.mul)))  # [3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]

for i in itertools.chain('123', '24'):
    print(i)  # 1 2 3 2 4
print(list(itertools.chain('I', 'love', 'you')))  # ['I', 'l', 'o', 'v', 'e', 'y', 'o', 'u']
print(list(itertools.chain.from_iterable(['I', 'love', 'you'])))  # ['I', 'l', 'o', 'v', 'e', 'y', 'o', 'u']

data = [1, 2, 3, 4]
print(list(itertools.combinations(data, 2)))  # [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
print(list(itertools.combinations_with_replacement(data,
                                                   2)))  # [(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]

print(list(itertools.compress(data, [1, 1, 1, 0])))  # [1, 2, 3]

import time

# 无限循环 1 3 5 7 9 ...
# for i in itertools.count(1, 2):
#     print(i)
#     time.sleep(0.2)

# 无限循环 1 2 3 4 1 2 3 4 ...
# for i in itertools.cycle(data):
#     print(i)
#     time.sleep(0.2)

# 重复两次 123 123
for i in itertools.repeat('123', 2):
    print(i)

# 无限循环 123 123 123 123,...
# for i in itertools.repeat('123'):
#     print(i)

print(list(itertools.dropwhile(lambda x: x < 5, [1, 2, 3, 7, 6, 5, 1])))  # [7, 6, 5, 1]
print(list(itertools.takewhile(lambda x: x < 5, [1, 2, 3, 7, 6, 5, 1])))  # [1, 2, 3]
print(list(itertools.filterfalse(lambda x: x < 5, [1, 2, 3, 7, 6, 5, 1])))  # [7, 6, 5]

for k, g in itertools.groupby('AAaaBBBbCcAA'):
    print(k, list(g))

for k, g, in itertools.groupby('AAaaBBBbCcAA', lambda x: x.upper()):
    print(k, list(g))

print(list(itertools.islice([1, 2, 3, 7, 6, 5, 1], 2)))  # [1, 2]
print(list(itertools.islice([1, 2, 3, 7, 6, 5, 1], 2, 5)))  # [3, 7, 6]
print(list(itertools.permutations([1, 2, 3], 2)))  # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
print(list(itertools.product([1, 2, 3],
                             [1, 2, 3])))  # [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
print(list(itertools.starmap(pow, [(1, 2), (2, 3), (4, 2)])))  # [1, 8, 16]

for i in itertools.tee([1, 2, 3, 4], 2):
    print(list(i))
iterator1, iterator2 = itertools.tee([1, 2, 3, 4, 5, 6, 7], 2)
print(list(iterator1))  # [1, 2, 3, 4, 5, 6, 7]
# 走到最后，迭代完毕，返回空
print(list(iterator1))  # []
print(list(iterator2))  # [1, 2, 3, 4, 5, 6, 7]

print(list(itertools.zip_longest([1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5],
                                 fillvalue=0)))  # [(1, 1, 1), (2, 2, 2), (3, 3, 3), (0, 4, 4), (0, 0, 5)]
